<template>
  <div class="forgetPassword-wrapper">
    <h1>企业人事管理系统</h1>
    <div class="forgetPassword-container">
      <div class="forgetPassword-header">
        <h3 class="title">通过邮箱设置新密码</h3>
      </div>
      <!-- 表单 -->

      <a-form
        name="normal_login"
        :model="formState"
        class="login-form"
        ref="formRef"
        :rules="rules"
        @finish="onFinish"
      >
        <!-- 邮箱 -->
        <a-form-item label="邮　　箱" name="email" hasFeedback>
          <a-input
            v-model:value="formState.email"
            placeholder="请输入邮箱账号"
            @change="checkEmail"
          >
            <template #prefix>
              <UserOutlined class="site-form-item-icon" />
            </template>
          </a-input>
        </a-form-item>

        <!-- 设置密码 -->
        <a-form-item label="设置密码" name="newPassword" hasFeedback>
          <a-input-password
            v-model:value="formState.newPassword"
            placeholder="请输入新密码"
          >
            <template #prefix>
              <LockOutlined class="site-form-item-icon" />
            </template>
          </a-input-password>
        </a-form-item>

        <!-- 确认密码 -->
        <a-form-item label="确认密码" name="confirmPassword" hasFeedback>
          <a-input-password
            v-model:value="formState.confirmPassword"
            placeholder="请确认密码"
          >
            <template #prefix>
              <LockOutlined class="site-form-item-icon" />
            </template>
          </a-input-password>
        </a-form-item>

        <!-- 验证码 -->
        <a-form-item label="验 证 码" name="captcha" class="item-captcha">
          <a-input-group compact>
            <a-input
              v-model:value="formState.captcha"
              class="captcha-input"
              placeholder="请输入验证码"
              :disabled="isDisabledCaptchaInputRef"
            >
              <template #prefix>
                <ClockCircleOutlined />
              </template>
            </a-input>
            <a-button
              type="primary"
              class="captcha-button"
              :disabled="isDisabledCaptcha"
              @click="handleSendCaptcha"
              >{{
                isSendedCaptcha ? `${currentCount}秒后重新发送` : "发送验证码"
              }}</a-button
            >
          </a-input-group>
        </a-form-item>

        <!-- 立即登录 -->

        <span class="login-now">
          <router-link to="/user/login" class="login-now-link">
            立即登录
          </router-link>
        </span>

        <!-- 重置 -->
        <a-form-item>
          <a-button
            type="primary"
            html-type="submit"
            class="login-form-button"
            :disabled="disabledResetBtn"
          >
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, computed, toRaw, ref } from "vue";
import {
  UserOutlined,
  LockOutlined,
  ClockCircleOutlined
} from "@ant-design/icons-vue";
import { Form, message } from "ant-design-vue";
import { useUserStore } from "@/store/user";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { FormInstance, Rule } from "ant-design-vue/lib/form";
import { getEmailCode_API } from "@/apis/user";
import apis from "@/apis/index";
import {
  useEmail,
  useNewPassword,
  useConfirmPassword,
  useCaptcha
} from "@/hooks/ForgetPassword/index";
// hook函数
const { emailStrRef, emailRulesArr } = useEmail();
const { newPasswordStrRef, newPasswordRulesArr } = useNewPassword();
const { confirmPasswordStrRef, confirmPasswordRulesArr } =
  useConfirmPassword(newPasswordStrRef);
const { captchaStrRef, captchaRulesArr } = useCaptcha();
interface FormState {
  // 邮箱账号
  email: string;
  // 新密码
  newPassword: string;
  // 确认密码
  confirmPassword: string;
  // 验证码
  captcha: string;
}
const formState = reactive<FormState>({
  email: emailStrRef,
  newPassword: newPasswordStrRef,
  confirmPassword: confirmPasswordStrRef,
  captcha: captchaStrRef
});

const formRef = ref<FormInstance>();
// 禁用发送验证码按钮
const isDisabledCaptcha = ref<boolean>(true);
// 是否是已经发送了验证码的状态
const isSendedCaptcha = ref<boolean>(false);
// 倒计时总时长
const currentCount = ref<number>(60);
// 是否禁用验证码输入框
const isDisabledCaptchaInputRef = ref<boolean>(true);
// 实例化userStore
const userStore = useUserStore();
// 实例化路由
const router = useRouter();
// 开始倒计时
const startCountDown = () => {
  const timer = setInterval(() => {
    // 判断是否倒计时结束
    if (currentCount.value === 0) {
      clearInterval(timer);
      // 1.修改发送状态
      isSendedCaptcha.value = false;
      // 2.修改禁用状态
      isDisabledCaptcha.value = false;
      // 3.当前时间重新回到最大时间
      currentCount.value = 60;
      return;
    }
    // 倒计时
    currentCount.value--;
  }, 1000);
};
// 处理-发送验证密码
const handleSendCaptcha = async () => {
  // 发送验证码
  try {
    // 1.判断邮箱是否存在数据库中
    const isExist = await apis.user.isExists_API({ email: formState.email });
    if (!isExist) {
      // 邮箱不存在
      message.error("邮箱账号无效");
      // 重置表单
      formRef.value.resetFields();
      return;
    }
    // 2.有效则发送验证码，无效则提示邮箱无效
    // 2.1修改已经发送的状态
    isSendedCaptcha.value = true;
    // 修改输入框的禁用状态
    isDisabledCaptchaInputRef.value = false;
    // 2.2按钮设为禁用状态
    isDisabledCaptcha.value = true;
    // 2.3开始倒计时
    startCountDown();
    const resData = await getEmailCode_API(formState.email);
    if (resData) {
      sessionStorage.clear();
      sessionStorage.setItem("captcha", resData.code);
      message.success("验证码发送成功，请注意查收");
    }
  } catch (error) {
    console.log(error, "error");
  }
};
// 提交成功
const onFinish = async (values: any) => {
  // 3.验证填写的验证码是否与发送的一致
  const code = sessionStorage.getItem("captcha") || "";
  if (formState.captcha !== code) {
    // 验证码不一致
    message.error("验证码错误，请重新发送");
    return;
  }
  // 4.修改密码，并反馈回来，成功则提示成功，并跳回登录页，失败则提示失败，并清空表单
  const bool = await apis.user.updateUserPassword_API(
    formState.email,
    formState.newPassword
  );
  if (!bool) {
    // 修改失败
    message.error("修改用户密码失败，请稍后尝试");
    formRef.value.resetFields();
    // 修改验证码输入框的禁用状态
    isDisabledCaptchaInputRef.value = false;
    return;
  }
  // 修改成功
  message.success("修改用户密码成功，即将跳转到登录页面");
  setTimeout(() => {
    router.push({ path: "/user/login" });
  }, 1500);
};
// 计算属性-禁用重置按钮
const disabledResetBtn = computed(() => {
  return !(
    formState.email &&
    formState.newPassword &&
    formState.confirmPassword &&
    formState.captcha
  );
});
// 计算属性-禁用发送送验证码按钮
const disabledCaptchaBtn = computed(() => {
  return !formState.email;
});

// 验证规则
const rules: Record<string, Rule[]> = {
  // 邮箱
  email: emailRulesArr,
  // 设置密码
  newPassword: newPasswordRulesArr,
  // 确认密码
  confirmPassword: confirmPasswordRulesArr,
  // 验证码
  captcha: captchaRulesArr
};
// 是否禁用发送验证码按钮（通过监听email的输入值是否通过验证）
const checkEmail = async (value: string) => {
  try {
    // 获取email的验证结果
    const res = await formRef.value.validateFields(["email"]);
    if (res) {
      // email验证通过，打开发送验证码的禁用状态
      isDisabledCaptcha.value = false;
    }
  } catch (error) {
    isDisabledCaptcha.value = true;
  }
};
</script>

<style lang="less" scoped>
@import "./index.less";
</style>
